package com.rainy.cloud.gateway.limiter;

import com.rainy.cloud.gateway.limiter.factory.RainyRateLimiterGatewayFilterFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.cloud.gateway.filter.ratelimit.RedisRateLimiter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.core.ReactiveRedisTemplate;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.validation.Validator;

import java.util.List;

/**
 * @author user
 */
@Configuration
public class LimiterConfig {

    @Bean
    @Primary
    public RedisRateLimiter rainyRateLimiter(
            ReactiveRedisTemplate<String, String> redisTemplate,
            @Qualifier(RedisRateLimiter.REDIS_SCRIPT_NAME) RedisScript<List<Long>> redisScript,
            Validator validator) {
        RedisRateLimiter redisRateLimiter = new RainyRateLimiter(redisTemplate, redisScript, validator);
        return redisRateLimiter;
    }

    @Bean
    public RainyRateLimiterGatewayFilterFactory rateLimiterGatewayFilterFactory(
            RainyRateLimiter rainyRateLimiter, KeyResolver keyResolver) {
        return new RainyRateLimiterGatewayFilterFactory(rainyRateLimiter, keyResolver);
    }
}
